package com.zrwl.poscloud.xo.service.impl;

import com.zrwl.poscloud.base.constants.GradeTeacherConstants;
import com.zrwl.poscloud.base.entity.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.DeptUtil;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.EmployeeMapper;
import com.zrwl.poscloud.xo.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import com.zrwl.poscloud.xo.mapper.GradeTeacherRMapper;
import com.zrwl.poscloud.xo.vo.GradeTeacherRVO;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 教师 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2023-02-27
 */
@Service
public class GradeTeacherRServiceImpl extends SuperServiceImpl<GradeTeacherRMapper, GradeTeacherR> implements GradeTeacherRService {

    @Autowired
    private GradeTeacherRService gradeTeacherRService;
    @Autowired
    private GradeService gradeService;
    @Resource
    private GradeTeacherRMapper gradeTeacherRMapper;
    @Autowired
    private EmployeeService employeeService;
    @Resource
    private EmployeeMapper employeeMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private CompanyService companyService;

    @Override
    public IPage<GradeTeacherRVO> getPageList(GradeTeacherRVO gradeTeacherRVO) {
        Page<GradeTeacherR> page = new Page<>();
        page.setCurrent(gradeTeacherRVO.getCurrentPage());
        page.setSize(gradeTeacherRVO.getPageSize());
        IPage<GradeTeacherRVO> pageList = gradeTeacherRMapper.getPageList(page, gradeTeacherRVO);
        List<GradeTeacherRVO> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<GradeTeacherRVO> getAllList(GradeTeacherRVO gradeTeacherRVO) {
        List<GradeTeacherRVO> list = gradeTeacherRMapper.getAllList(gradeTeacherRVO);
        return list;
    }

    @Override
    public String add(GradeTeacherRVO gradeTeacherRVO) {
        GradeTeacherR entity = new GradeTeacherR();
        BeanUtils.copyProperties(gradeTeacherRVO, entity, SysConf.STATUS);
        entity.setBeginTime(new Date());
        entity.insert();
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(GradeTeacherRVO gradeTeacherRVO) {
        GradeTeacherR entity = gradeTeacherRService.getById(gradeTeacherRVO.getUid());
        BeanUtils.copyProperties(gradeTeacherRVO, entity);
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(GradeTeacherRVO gradeTeacherRVO) {
        GradeTeacherR entity = gradeTeacherRService.getById(gradeTeacherRVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    @Transactional
    public String batchAdd(List<GradeTeacherRVO> list) {
        if (list.size() == 0) {
            throw new RuntimeException("添加代课教师失败");
        }
        for (GradeTeacherRVO gradeTeacherRVO : list) {
            if (StringUtils.isNotBlank(gradeTeacherRVO.getUid() )) {
                GradeTeacherR gradeTeacherR = gradeTeacherRService.getById(gradeTeacherRVO.getUid());
                if (!gradeTeacherR.getEmployeeUid().equals(gradeTeacherRVO.getEmployeeUid())) {
                    gradeTeacherR.setEndTime(new Date());
                    gradeTeacherR.setStatus(GradeTeacherConstants.freeze);
                    gradeTeacherR.updateById();
                    gradeTeacherRVO.setUid(null);
                }
            }
            if (StringUtils.isBlank(gradeTeacherRVO.getUid()) && StringUtils.isNotBlank(gradeTeacherRVO.getEmployeeUid())) {
                if (StringUtils.isEmpty(gradeTeacherRVO.getGradeUid()) || StringUtils.isEmpty(gradeTeacherRVO.getGradeUid().trim())) {
                    throw new RuntimeException("班级不可为空");
                }
                gradeTeacherRVO.setBeginTime(new Date());
                gradeTeacherRVO.setEndTime(null);
                gradeTeacherRService.add(gradeTeacherRVO);
            }

        }
        return ResultUtil.successWithMessage("导入成功");
    }

    @Override
    public List<GradeTeacherRVO> getHistoryRecordList(GradeTeacherRVO gradeTeacherRVO) {
        List<GradeTeacherRVO> list = gradeTeacherRMapper.getHistoryRecordList(gradeTeacherRVO);
        return list;
    }

    @Override
    public GradeTeacherR getTeacherBySubjectTypeAndGrade(String gradeUid, int subjectType) {
        return gradeTeacherRMapper.getTeacherBySubjectTypeAndGrade(gradeUid, subjectType);
    }

    @Override
    @Transactional
    public String singleImport(GradeTeacherRVO gradeTeacherRVO, Grade grade) {
        String companyCode;
        Dept dept = gradeService.getDeptByUid(grade.getUid());
        if(dept == null){
            throw new RuntimeException("该班级错误");
        }
        if(dept.getLevel() == 1){
            Company company = companyService.getByCode(DeptUtil.getCompanyFull(DeptUtil.getCompanyShortCode(dept.getCompanyCode(), String.valueOf((dept.getLevel() - 1)))));
            if(!gradeTeacherRVO.getSuperDeptName().equals(company.getShortName()) || !gradeTeacherRVO.getSuperDeptName().equals(company.getFullName())){
                throw new RuntimeException("上级部门不存在");
            }
        }
        Dept superDept = deptService.getDeptByCode(DeptUtil.getCompanyFull(DeptUtil.getCompanyShortCode(dept.getCompanyCode(), String.valueOf((dept.getLevel() - 1)))));
        if(!gradeTeacherRVO.getSuperDeptName().equals(superDept.getName())){
            throw new RuntimeException("上级部门不存在");
        }
        if(!gradeTeacherRVO.getGradeName().equals(dept.getName())){
            throw new RuntimeException("班级名称不匹配");
        }
        companyCode = dept.getCompanyCode();
        if(StringUtils.isBlank(gradeTeacherRVO.getEmployeeName())){
            throw new RuntimeException("教师姓名不可为空");
        }
        String name = gradeTeacherRVO.getEmployeeName();
        String suffix = null;
        if(name.contains("(")){
            suffix = name.split("\\(")[1].substring(0,name.split("\\(")[1].length()-1);
            name = name.split("\\(")[0];
        }
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_code",DeptUtil.getCompanyFull(DeptUtil.getCompanyShortCode(companyCode,String.valueOf(Integer.parseInt(DeptUtil.getCompanyLevel(companyCode))-1))));
        queryWrapper.eq("name",name);
        if(StringUtils.isNotBlank(suffix)){
            queryWrapper.eq("name_end_with",suffix);
        }
        queryWrapper.eq(SQLConf.STATUS,EStatus.ENABLE);
        List<Employee> list = employeeService.list(queryWrapper);
        if(list.size()>1){
            throw new RuntimeException("该教师同名存在请先进行同名处理");
        }
        if(list.size() == 0){
            throw new RuntimeException("该教师不存在");
        }
        GradeTeacherR teacher = gradeTeacherRService.getTeacherBySubjectTypeAndGrade(grade.getUid(), gradeTeacherRVO.getSubjectType());
        if(teacher != null){
            teacher.setEndTime(new Date());
            teacher.setStatus(GradeTeacherConstants.freeze);
            teacher.updateById();
        }
        Employee employee = list.get(0);
        gradeTeacherRVO.setEmployeeUid(employee.getUid());
        gradeTeacherRVO.setBeginTime(new Date());
        return add(gradeTeacherRVO);
    }

    @Override
    public GradeTeacherR getGradeTeacherByEmployeeUid(String employeeUid, int subjectType) {
        GradeTeacherR gradeTeacherR = gradeTeacherRMapper.getGradeTeacherByEmployeeUid(employeeUid, subjectType);
        if(gradeTeacherR == null){
            throw new RuntimeException("该班级暂无班主任");
        }
        return gradeTeacherR;
    }

    @Override
    public List<GradeTeacherRVO> getEmployeeTeacher(GradeTeacherRVO gradeTeacherRVO) {
        return gradeTeacherRMapper.getEmployeeTeacher(gradeTeacherRVO);
    }

    /**
     * 根据教师和学生获取教师（权限）
     *
     * @param studentUid 学生
     * @param teacherUid 教师
     * @return 教师（权限）
     */
    @Override
    public GradeTeacherR getTeacherAuthorityByTeacherAndStudent(String studentUid, String teacherUid) {
        GradeTeacherR gradeTeacherR = gradeTeacherRMapper.getTeacherAuthorityByTeacherAndStudent(studentUid, teacherUid);
        return gradeTeacherR;
    }

    @Override
    public GradeTeacherR getGradeTeacherR(String teacherUid, int subjectType) {
        GradeTeacherR gradeTeacherR = gradeTeacherRMapper.getGradeTeacher(teacherUid, subjectType);
        if(gradeTeacherR == null){
            throw new RuntimeException("该班级暂无班主任");
        }
        return gradeTeacherR;
    }
}
